package logic

import (
	"context"
	"strings"

	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/user/model"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetAttachmentLogListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetAttachmentLogListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetAttachmentLogListLogic {
	return &BackendGetAttachmentLogListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// #25.02.27#
func (l *BackendGetAttachmentLogListLogic) BackendGetAttachmentLogList(in *user.BackendAttachmentLogListReq) (*user.BackendAttachmentLogListResp, error) {
	logx.Infof("BackendGetAttachmentLogList : %+v ", in)
	var orderBys []string
	if len(in.OrderBy) > 0 {
		for _, orderBy := range in.OrderBy {
			order := " ASC"
			if orderBy.Order == "1" {
				order = " DESC"
			}
			if orderBy.Field == "id" {
				orderBys = append(orderBys, model.UserAttachmentRelationshipColumns.AttachmentRelationshipID+order)
			}
		}
	}

	filterMap := make(map[string]map[string][]any)
	if in.Ids != nil && len(strings.TrimSpace(*in.Ids)) > 0 {
		if ids := modelx.UniqueInterfaces(*in.Ids, 64); len(ids) > 0 {
			filterMap[model.UserAttachmentRelationshipColumns.AttachmentRelationshipID] = map[string][]any{
				"in": ids,
			}
		}
	}

	var orderBy string
	if len(orderBys) > 0 {
		orderBy = strings.Join(orderBys, ",")
	}

	res, _, err := l.svcCtx.CurrentUser.GetMedia(l.ctx, model.M{
		//"offset": in.Offset,
		//"limit":  in.Limit,
		// "search":  in.Search,
		"orderBy": orderBy,
		//"select":  strings.Join(selectCols, ","),
	}, -1, filterMap)
	if err != nil {
		return nil, err
	}

	var resp = &user.BackendAttachmentLogListResp{}
	if len(res) > 0 {
		for _, v := range res {
			resp.List = append(resp.List, &user.AttachmentLogInfo{
				Id:           pointy.GetPointer(v.AttachmentRelationshipID),
				UserId:       pointy.GetPointer(v.UserID),
				Type:         pointy.GetPointer(uint32(v.Type)),
				AttachmentId: pointy.GetPointer(v.AttachmentID),
				Thumbnail:    pointy.GetPointer(uint32(v.AttachmentThumbnail)),
				Order:        pointy.GetPointer(uint64(v.AttachmentOrder)),
				Source:       pointy.GetPointer(v.AttachmentSource),
				Url:          pointy.GetPointer(v.AttachmentImageURL),
				Alt:          pointy.GetPointer(v.AttachmentImageAlt),
				Meta:         pointy.GetPointer(v.AttachmentImageMeta),
			})
		}
	}

	return resp, nil
}
